package com.beta.auth.service;

import com.beta.auth.constants.BusinessConstants;
import com.beta.auth.dto.auth.AuthDto;
import com.beta.auth.dto.auth.WXAuthState;
import com.beta.auth.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author gwqin
 * @description
 * @date 2023-07-13 15:08
 */
@Slf4j
@Component
public abstract class AbstractAuthService implements AuthService {

    /**
     * JWT中保存用户ID的字段名称
     */
    protected static final String USERID = "userId";

    /**
     * JWT中保存签发时间的字段名称
     */
    protected static final String CT = "ct";


    @Override
    public void oAuth(AuthDto authDto, WXAuthState authState, HttpServletRequest request, HttpServletResponse response) {
        invokeAuth(authDto, authState, request, response);
    }

    public abstract void invokeAuth(AuthDto authDto, WXAuthState authState, HttpServletRequest request, HttpServletResponse resp);

    /**
     * 校验code和state是否正确
     *
     * @param authState
     * @param authDto
     * @return
     */
    public boolean checkAuthCode(WXAuthState authState, AuthDto authDto, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(authDto.getCode())) {
            // 业务端首次进入授权接口
            return false;
        }

        // 腾讯回调进入授权接口
        if (!authState.getState().equals(authDto.getState())) {
            log.warn("数据异常，authState.state={}, authDto.state={}", authState.getState(), authDto.getState());
            ResponseUtils.toErrPage(BusinessConstants.SYSTEM_ERROR_MSG, BusinessConstants.PARAMS_ERROR_CODE, response);
            // 标识未异常状态
            authDto.setAc(-1);
            return false;
        }
        authDto.setAc(1);
        return true;
    }
}
